# -*- coding: utf-8 -*-
# Import Odoo models and fields
from odoo import models, fields, api, _


class SForecastMaterialSummary(models.Model):
    _name = 's.forecast.material.summary'  # Technical name of the model
    _description = 'Forecast Material Summary'  # Description of the model

    # Field definitions
    forecast_order_id = fields.Many2one(
        's.forecast.order',
        string='Forecast Order',
        required=True,
        ondelete='cascade',
        index=True
    )
    material_id = fields.Many2one(
        'product.product',
        string='Material',
        required=True
    )
    total_required_quantity = fields.Float(
        string='Total Required Quantity',
        required=True,
        default=0.0
    )
    on_hand_quantity = fields.Float(
        string='On Hand Quantity',
        compute='_compute_quantities',
        store=True,
        help="Current on-hand quantity of this material."
    )
    suggested_purchase_quantity = fields.Float(
        string='Suggested Purchase Quantity',
        compute='_compute_quantities',
        store=True,
        help="Suggested purchase quantity = Total Required Quantity - On Hand Quantity (zero if the result is less than zero)."
    )
    # NEW: Quantity already procured for this material against this forecast
    procured_quantity = fields.Float(
        string='Procured Quantity',
        default=0.0,
        help="Quantity of this material already procured for this forecast. This needs to be updated manually or via advanced integration with PO receipts."
    )
    # NEW: Remaining quantity to purchase
    remaining_purchase_quantity = fields.Float(
        string='Remaining Purchase Quantity',
        compute='_compute_quantities',
        store=True,
        help="Remaining quantity to purchase = Suggested Purchase Quantity - Procured Quantity."
    )

    # Compute on-hand quantity, suggested purchase quantity, and remaining purchase quantity
    @api.depends('material_id', 'total_required_quantity', 'procured_quantity')
    def _compute_quantities(self):
        for rec in self:
            if rec.material_id:
                rec.on_hand_quantity = rec.material_id.qty_available
                rec.suggested_purchase_quantity = max(0.0, rec.total_required_quantity - rec.on_hand_quantity)
                rec.remaining_purchase_quantity = max(0.0, rec.suggested_purchase_quantity - rec.procured_quantity)
            else:
                rec.on_hand_quantity = 0.0
                rec.suggested_purchase_quantity = 0.0
                rec.remaining_purchase_quantity = 0.0
